<?php
// +----------------------------------------------------------------------
// | ThinkBLOG (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author nicholas <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: common.php 143 2012-04-27 06:37:38Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


if (! defined ( 'THINK_PATH' ))
	die ( 'Hacking attempt' );

function taddslashes($string, $force = 1) {
	if (is_array ( $string )) {
		$keys = array_keys ( $string );
		foreach ( $keys as $key ) {
			$val = $string [$key];
			unset ( $string [$key] );
			$string [addslashes ( $key )] = taddslashes ( $val, $force );
		}
	} else {
		$string = addslashes ( $string );
	}
	return $string;
}

function tstripslashes($string) {
	if (empty ( $string ))
		return $string;
	if (is_array ( $string )) {
		foreach ( $string as $key => $val ) {
			$string [$key] = tstripslashes ( $val );
		}
	} else {
		$string = stripslashes ( $string );
	}
	return $string;
}

function tregisterglobalsoff($string) {
	foreach ( $string as $key => $val )
		unset ( ${$key} );
}

/**
 * 获得当前格林威治时间的时间戳
 *
 * @return  integer
 */
function tgmtime() {
	static $time = NULL;
	if ($time === NULL)
		$time = time () - date ( 'Z' );
	return $time;
}

function tget_client_ip() {
	$ip = $_SERVER ['REMOTE_ADDR'];
	if (isset ( $_SERVER ['HTTP_CLIENT_IP'] ) && preg_match ( '/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER ['HTTP_CLIENT_IP'] )) {
		$ip = $_SERVER ['HTTP_CLIENT_IP'];
	} elseif (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] ) && preg_match_all ( '#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER ['HTTP_X_FORWARDED_FOR'], $matches )) {
		foreach ( $matches [0] as $xip ) {
			if (! preg_match ( '#^(10|172\.16|192\.168)\.#', $xip )) {
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}

function tauthcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	global $_T;
	$ckey_length = 4;
	
	$key = md5 ( $key ? $key : $_T ['authkey'] );
	$keya = md5 ( substr ( $key, 0, 16 ) );
	$keyb = md5 ( substr ( $key, 16, 16 ) );
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
	
	$cryptkey = $keya . md5 ( $keya . $keyc );
	$key_length = strlen ( $cryptkey );
	
	$string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
	$string_length = strlen ( $string );
	
	$result = '';
	$box = range ( 0, 255 );
	
	$rndkey = array ();
	for($i = 0; $i <= 255; $i ++) {
		$rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
	}
	
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box [$i] + $rndkey [$i]) % 256;
		$tmp = $box [$i];
		$box [$i] = $box [$j];
		$box [$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box [$a]) % 256;
		$tmp = $box [$a];
		$box [$a] = $box [$j];
		$box [$j] = $tmp;
		$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
	}
	
	if ($operation == 'DECODE') {
		if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
			return substr ( $result, 26 );
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
	}

}

function tformhash($specialadd = '') {
	global $_T;
	return substr ( md5 ( substr ( $_T ['timestamp'], 0, - 7 ) . $_T ['username'] . $_T ['userid'] . $_T ['authkey'] . $specialadd ), 8, 8 );
}

function trandom($length, $numeric = 0) {
	$seed = base_convert ( md5 ( microtime () . $_SERVER ['DOCUMENT_ROOT'] ), 16, $numeric ? 10 : 35 );
	$seed = $numeric ? (str_replace ( '0', '', $seed ) . '012340567890') : ($seed . 'zZ' . strtoupper ( $seed ));
	$hash = '';
	$max = strlen ( $seed ) - 1;
	for($i = 0; $i < $length; $i ++) {
		$hash .= $seed {mt_rand ( 0, $max )};
	}
	return $hash;
}

function tupdatesession($force = false) {
	
	global $_T;
	static $updated = false;
	
	if (! $updated) {
		$t = ThinkBLOG::getInstance ();
		if ($_T ['userid']) {
			if ($_T ['cookie'] ['ulastactivity']) {
				$ulastactivity = tauthcode ( $_T ['cookie'] ['ulastactivity'], 'DECODE' );
			} else {
				$ulastactivity = $_T ['users'] ['lastactivity'];
				cookie ( 'ulastactivity', tauthcode ( $ulastactivity, 'ENCODE' ), 31536000 );
			}
		}
		$oltimespan = 10;
		$lastolupdate = $t->session->var ['lastolupdate'];
		if ($_T ['userid'] && $oltimespan && TIMESTAMP - ($lastolupdate ? $lastolupdate : $ulastactivity) > $oltimespan * 60) {
			$t->session->set ( 'lastolupdate', TIMESTAMP );
		}
		
		foreach ( $t->session->var as $k => $v ) {
			if (isset ( $_T ['users'] [$k] ) && $k != 'lastactivity')
				$t->session->set ( $k, $_T ['users'] [$k] );
		}
		
		foreach ( $_T ['action'] as $k => $v ) {
			$t->session->set ( $k, $v );
		}
		
		$t->session->update ();
		
		$updated = true;
	}
	
	return $updated;
}

function tmessage($message) {
	echo <<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Error</title>
<style type="text/css">
body{background:#f7fbe9;font-family:"Lucida Grande","Lucida Sans Unicode",Tahoma,Verdana;}#error{background:#333;width:360px;margin:100px auto;color:#fff;padding:10px;-moz-border-radius-topleft:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-bottomright:4px;-webkit-border-top-left-radius:4px;-webkit-border-top-right-radius:4px;-webkit-border-bottom-left-radius:4px;-webkit-border-bottom-right-radius:4px;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-left-radius:4px;border-bottom-right-radius:4px;}h1{padding:10px;margin:0;font-size:36px;}p{padding:0 20px 20px 20px;margin:0;font-size:12px;}
</style>
</head>
<body>
<div id="error">
  <h1>Error</h1>
  <p>{$message}</p>
</div>
</body>
</html>
EOT;
	die ();
}

function ipbanned($onlineip) {
	//TODO
}

function trandstring($length, $specialChars = false) {
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	if ($specialChars) {
		$chars .= '!@#$%^&*()';
	}
	
	$result = '';
	$max = strlen ( $chars ) - 1;
	for($i = 0; $i < $length; $i ++) {
		$result .= $chars [rand ( 0, $max )];
	}
	return $result;
}

function tstrlen($str) {
	if (function_exists ( 'mb_get_info' )) {
		return mb_strlen ( $str, 'UTF-8' );
	} else {
		preg_match_all ( "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $str, $info );
		return sizeof ( $info [0] );
	}
}

function tfilter_search_query($query) {
	return str_replace ( array ('%', '?', '*', '/', '{', '}' ), '', $query );
}

function tremove_xss($val) {
	// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
	// this prevents some character re-spacing such as <java\0script>
	// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
	$val = preg_replace ( '/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val );
	
	// straight replacements, the user should never need these since they're normal characters
	// this prevents like <IMG SRC=@avascript:alert('XSS')>
	$search = 'abcdefghijklmnopqrstuvwxyz';
	$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$search .= '1234567890!@#$%^&*()';
	$search .= '~`";:?+/={}[]-_|\'\\';
	for($i = 0; $i < strlen ( $search ); $i ++) {
		// ;? matches the ;, which is optional
		// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
		

		// @ @ search for the hex values
		$val = preg_replace ( '/(&#[xX]0{0,8}' . dechex ( ord ( $search [$i] ) ) . ';?)/i', $search [$i], $val ); // with a ;
		// @ @ 0{0,7} matches '0' zero to seven times
		$val = preg_replace ( '/(&#0{0,8}' . ord ( $search [$i] ) . ';?)/', $search [$i], $val ); // with a ;
	}
	
	// now the only remaining whitespace attacks are \t, \n, and \r
	$ra1 = array ('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base' );
	$ra2 = array ('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload' );
	$ra = array_merge ( $ra1, $ra2 );
	
	$found = true; // keep replacing as long as the previous round replaced something
	while ( $found == true ) {
		$val_before = $val;
		for($i = 0; $i < sizeof ( $ra ); $i ++) {
			$pattern = '/';
			for($j = 0; $j < strlen ( $ra [$i] ); $j ++) {
				if ($j > 0) {
					$pattern .= '(';
					$pattern .= '(&#[xX]0{0,8}([9ab]);)';
					$pattern .= '|';
					$pattern .= '|(&#0{0,8}([9|10|13]);)';
					$pattern .= ')*';
				}
				$pattern .= $ra [$i] [$j];
			}
			$pattern .= '/i';
			$replacement = substr ( $ra [$i], 0, 2 ) . '<x>' . substr ( $ra [$i], 2 ); // add in <> to nerf the tag
			$val = preg_replace ( $pattern, $replacement, $val ); // filter out the hex tags
			if ($val_before == $val) {
				// no replacements were made, so exit the loop
				$found = false;
			}
		}
	}
	return $val;
}

function tsafe_url($url) {
	//~ 针对location的xss过滤, 因为其特殊性无法使用removeXSS函数
	//~ fix issue 66
	$params = parse_url ( str_replace ( array ("\r", "\n" ), '', $url ) );
	
	/** 禁止非法的协议跳转 */
	if (isset ( $params ['scheme'] )) {
		if (! in_array ( $params ['scheme'], array ('http', 'https' ) )) {
			return;
		}
	}
	
	/** 过滤解析串 */
	$params = array_map ( 'tremove_url_xss', $params );
	return tbuild_url ( $params );
}

function tremove_url_xss($string) {
	$string = str_replace ( array ('%0d', '%0a' ), '', strip_tags ( $string ) );
	return preg_replace ( array ("/\(\s*(\"|')/i", "/(\"|')\s*\)/i" ), '', $string );
}

function tbuild_url($params) {
	return (isset ( $params ['scheme'] ) ? $params ['scheme'] . '://' : NULL) . (isset ( $params ['user'] ) ? $params ['user'] . (isset ( $params ['pass'] ) ? ':' . $params ['pass'] : NULL) . '@' : NULL) . (isset ( $params ['host'] ) ? $params ['host'] : NULL) . (isset ( $params ['port'] ) ? ':' . $params ['port'] : NULL) . (isset ( $params ['path'] ) ? $params ['path'] : NULL) . (isset ( $params ['query'] ) ? '?' . $params ['query'] : NULL) . (isset ( $params ['fragment'] ) ? '#' . $params ['fragment'] : NULL);
}

function tis_ajax() {
	if (isset ( $_SERVER ['HTTP_X_REQUESTED_WITH'] )) {
		if ('xmlhttprequest' == strtolower ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ))
			return true;
	}
	if (! empty ( $_POST [C ( 'VAR_AJAX_SUBMIT' )] ) || ! empty ( $_GET [C ( 'VAR_AJAX_SUBMIT' )] ))
		// 判断Ajax方式提交
		return true;
	return false;
}

function tnum_bitunit($num) {
	$bitunit = array (' B', ' KB', ' MB', ' GB' );
	for($key = 0, $count = count ( $bitunit ); $key < $count; $key ++) {
		if ($num >= pow ( 2, 10 * $key ) - 1) { // 1024B 会显示为 1KB
			$num_bitunit_str = (ceil ( $num / pow ( 2, 10 * $key ) * 100 ) / 100) . " $bitunit[$key]";
		}
	}
	return $num_bitunit_str;
}

function tlocal_date($format, $time = NULL) {
	$timezone = C ( 'timezone' );
	
	if ($time === NULL) {
		$time = tgmtime ();
	} elseif ($time <= 0) {
		return '';
	}
	
	$time += ($timezone * 3600);
	
	return date ( $format, $time );
}

function tget_domain() {
	$protocol = thttp ();
	if (isset ( $_SERVER ['HTTP_X_FORWARDED_HOST'] )) {
		$host = $_SERVER ['HTTP_X_FORWARDED_HOST'];
	} elseif (isset ( $_SERVER ['HTTP_HOST'] )) {
		$host = $_SERVER ['HTTP_HOST'];
	} else {
		if (isset ( $_SERVER ['SERVER_PORT'] )) {
			$port = ':' . $_SERVER ['SERVER_PORT'];
			
			if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) {
				$port = '';
			}
		} else {
			$port = '';
		}
		if (isset ( $_SERVER ['SERVER_NAME'] )) {
			$host = $_SERVER ['SERVER_NAME'] . $port;
		} elseif (isset ( $_SERVER ['SERVER_ADDR'] )) {
			$host = $_SERVER ['SERVER_ADDR'] . $port;
		}
	}
	
	return $protocol . $host;
}

function turl() {
	$curr = dirname ( __SELF__ );
	$root = str_replace ( '\\', '/', $curr );
	if (substr ( $root, - 1 ) != '/') {
		$root .= '/';
	}
	return tget_domain () . $root;
}

function thttp() {
	return (isset ( $_SERVER ['HTTPS'] ) && (strtolower ( $_SERVER ['HTTPS'] ) != 'off')) ? 'https://' : 'http://';
}

function tgdversion() {
	static $version = - 1;
	
	if ($version >= 0) {
		return $version;
	}
	
	if (! extension_loaded ( 'gd' )) {
		$version = 0;
	} else {
		// 尝试使用gd_info函数
		if (PHP_VERSION >= '4.3') {
			if (function_exists ( 'gd_info' )) {
				$ver_info = gd_info ();
				preg_match ( '/\d/', $ver_info ['GD Version'], $match );
				$version = $match [0];
			} else {
				if (function_exists ( 'imagecreatetruecolor' )) {
					$version = 2;
				} elseif (function_exists ( 'imagecreate' )) {
					$version = 1;
				}
			}
		} else {
			if (preg_match ( '/phpinfo/', ini_get ( 'disable_functions' ) )) {
				/* 如果phpinfo被禁用，无法确定gd版本 */
				$version = 1;
			} else {
				// 使用phpinfo函数
				ob_start ();
				phpinfo ( 8 );
				$info = ob_get_contents ();
				ob_end_clean ();
				$info = stristr ( $info, 'gd version' );
				preg_match ( '/\d/', $info, $match );
				$version = $match [0];
			}
		}
	}
	
	return $version;
}

/**
 * 生成缩略名
 *
 * @access public
 * @param string $str 需要生成缩略名的字符串
 * @param string $default 默认的缩略名
 * @param integer $maxLength 缩略名最大长度
 * @return string
 */
function tslug_name($str, $default = NULL, $maxLength = 200) {
	$str = str_replace ( array ("'", ":", "\\", "/", '"' ), "", $str );
	$str = str_replace ( array ("+", ",", ' ', '，', ' ', ".", "?", "=", "&", "!", "<", ">", "(", ")", "[", "]", "{", "}" ), "-", $str );
	$str = trim ( $str, '-' );
	$str = empty ( $str ) ? $default : $str;
	
	return function_exists ( 'mb_get_info' ) ? mb_strimwidth ( $str, 0, 128, '', C ( 'THINKBLOG_CHARSET' ) ) : substr ( $str, 0, $maxLength );
}

/**
 +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 +----------------------------------------------------------
 * @static
 * @access public
 +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
	if (function_exists ( "mb_substr" )) {
		if ($suffix && strlen ( $str ) > $length)
			return mb_substr ( $str, $start, $length, $charset ) . "...";
		else
			return mb_substr ( $str, $start, $length, $charset );
	} elseif (function_exists ( 'iconv_substr' )) {
		if ($suffix && strlen ( $str ) > $length)
			return iconv_substr ( $str, $start, $length, $charset ) . "...";
		else
			return iconv_substr ( $str, $start, $length, $charset );
	}
	$re ['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re ['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re ['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re ['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all ( $re [$charset], $str, $match );
	$slice = join ( "", array_slice ( $match [0], $start, $length ) );
	if ($suffix)
		return $slice . "...";
	return $slice;
}

/**
 * 返回一个随机的名字
 *
 * @return  string      $str    随机名称
 */
function get_random_name() {
	$str = date ( 'Ymd' );
	for($i = 0; $i < 6; $i ++) {
		$str .= chr ( mt_rand ( 97, 122 ) );
	}
	return $str;
}

/**
 * 过滤备份数据中的'--'(from ecshop
 *
 * @access  public
 * @param
 * @return  void
 */
function remove_comment($var) {
	return (substr ( $var, 0, 2 ) != '--');
}

/**
 * 清除模版编译文件(from ecshop
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_compiled_files($ext = '') {
	return clear_tpl_files ( false, $ext );
}

/**
 * 清除缓存文件(from ecshop
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_cache_files($ext = '') {
	return clear_tpl_files ( true, $ext );
}

/**
 * 清除模版编译和缓存文件(from ecshop
 *
 * @access  public
 * @param   mix     $ext    模版文件名后缀
 * @return  void
 */
function clear_all_files($ext = '') {
	return clear_tpl_files ( false, $ext ) + clear_tpl_files ( true, $ext );
}

/**
 * 清除指定后缀的模板缓存或编译文件(from ecshop
 *
 * @access  public
 * @param  bool       $is_cache  是否清除缓存还是清出编译文件
 * @param  string     $ext       需要删除的文件名，不包含后缀
 *
 * @return int        返回清除的文件个数
 */
function clear_tpl_files($is_cache = true, $ext = '') {
	
	$dirs = array ();
	
	//文件目录
	$tmp_dir = CACHES_DIR;
	$compiled_dir = ROOT_PATH . 'App/Runtime/Cache/Home/';
	$compiled_admin_dir = ROOT_PATH . 'App/Runtime/Cache/Admin/';
	
	if ($is_cache) {
		$dirs [] = $tmp_dir;
	} else {
		$dirs [] = $compiled_dir;
		$dirs [] = $compiled_admin_dir;
	}
	
	$str_len = strlen ( $ext );
	$count = 0;
	
	foreach ( $dirs as $dir ) {
		$folder = @opendir ( $dir );
		
		if ($folder === false) {
			continue;
		}
		
		while ( $file = readdir ( $folder ) ) {
			if ($file == '.' || $file == '..' || $file == 'index.htm' || $file == 'index.html' || $file == 'index.php') {
				continue;
			}
			if (is_file ( $dir . $file )) {
				/* 如果有文件名则判断是否匹配 */
				$pos = ($is_cache) ? strrpos ( $file, '_' ) : strrpos ( $file, '.' );
				
				if ($str_len > 0 && $pos !== false) {
					$ext_str = substr ( $file, 0, $pos );
					
					if ($ext_str == $ext) {
						if (@unlink ( $dir . $file )) {
							$count ++;
						}
					}
				} else {
					if (@unlink ( $dir . $file )) {
						$count ++;
					}
				}
			}
		}
		closedir ( $folder );
	}
	
	return $count;
}

/**
 * 获得随机数
 *
 * @access     public
 * @param      string      $n       随机数长度
 * @return     string      $name    随机名称
 */
function get_uid($n) {
	$name = NULL;
	for($j = 0; $j < $n; $j ++) {
		srand ( ( double ) microtime () * 1000000 );
		$randname = rand ( ! $j ? 1 : 0, 9 );
		$name .= $randname;
	}
	return $name;
	$name = NULL;
}

/**
 * 获得随机大小
 *
 * @access     public
 * @param      string      $n       随机数长度
 * @return     array       
 */
function random_size($n) {
	/* 随机显示字体大小 */
	$arr = array ('0.8em', '0.9em', '1.0em', '1.1em', '1.2em', '1.3em' );
	if ($n > 6) {
		$n = $n % 6;
	}
	return $arr [$n];
}

function base64_url_encode($input) {
	return strtr ( base64_encode ( $input ), '+/=', '-_,' );
}

function base64_url_decode($input) {
	return base64_decode ( strtr ( $input, '-_,', '+/=' ) );
}

/**
 * 友好时间显示函数 参数$time 为要转换的时间戳 
 *
 */
function humanism_date($time) {
	if (! is_numeric ( $time ))
		return false;
	$_time = time () - $time;
	if ($_time < 5) {
		$show = '刚刚';
	} elseif ($_time < 60) {
		$show = $_time . '秒前';
	} elseif ($_time < 3600) {
		$show = floor ( $_time / 60 ) . '分钟前';
	} elseif ($_time < 3600 * 24) {
		$show = '今天 ' . date ( 'H:i', $time );
	} elseif ($_time < 3600 * 24 * 365) {
		$show = date ( 'n月d日 H:i', $time );
	} else {
		$show = date ( 'Y年n月d日 H:i', $time );
	}
	return $show;
}

/**
 * V($vRoute,$def_v=NULL);
 * APP:V($vRoute,$def_v=NULL);
 * 获取还原后的  $_GET ，$_POST , $_FILES $_COOKIE $_REQUEST $_SERVER $_ENV
 * 同名全局函数： V($vRoute,$def_v=NULL);
 * @param $vRoute	变量路由，规则为：“<第一个字母>[：变量索引/[变量索引]]
 * 例:	V('G:TEST/BB'); 表示获取 $_GET['TEST']['BB']
 * V('p'); 		表示获取 $_POST
 * V('c:var_name');表示获取 $_COOKIE['var_name']
 * @param $def_v
 * @param $setVar	是否设置一个变量
 * @return unknown_type
 */
function V($vRoute, $def_v = NULL, $setVar = false) {
	static $v;
	if (empty ( $v )) {
		$v = array ();
	}
	$vRoute = trim ( $vRoute );
	
	//强制初始化值
	if ($setVar) {
		$v [$vRoute] = $def_v;
		return true;
	}
	
	if (! isset ( $v [$vRoute] )) {
		$vKey = array ('C' => $_COOKIE, 'G' => $_GET, 'P' => $_POST, 'R' => $_REQUEST, 'F' => $_FILES, 'S' => $_SERVER, 'E' => $_ENV );
		if (empty ( $vKey ['R'] )) {
			$vKey ['R'] = array_merge ( $_COOKIE, $_GET, $_POST );
		}
		if (! preg_match ( "#^([cgprfse])(?::(.+))?\$#sim", $vRoute, $m ) || ! isset ( $vKey [strtoupper ( $m [1] )] )) {
			trigger_error ( "Can't parse var from vRoute: $vRoute ", E_USER_ERROR );
			return NULL;
		}
		
		//----------------------------------------------------------
		$m [1] = strtoupper ( $m [1] );
		$tv = $vKey [$m [1]];
		
		//----------------------------------------------------------
		if (empty ( $m [2] )) {
			$v [$vRoute] = ($m [1] == 'F' || $m [1] == 'S' || $m [1] == 'E') ? $tv : magic_var ( $tv );
		} elseif (empty ( $tv )) {
			return $def_v;
		} else {
			$vr = explode ( '/', $m [2] );
			while ( count ( $vr ) > 0 ) {
				$vk = array_shift ( $vr );
				if (! isset ( $tv [$vk] )) {
					return $def_v;
					break;
				}
				$tv = $tv [$vk];
			}
		}
		$v [$vRoute] = ($m [1] == 'F' || $m [1] == 'S' || $m [1] == 'E') ? $tv : magic_var ( $tv );
	}
	return $v [$vRoute];
}

/**
 * 根据用户服务器环境配置，递归还原变量
 * @param $mixed
 * @return 还原后的值
 */
function magic_var($mixed) {
	if ((function_exists ( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc ()) || @ini_get ( 'magic_quotes_sybase' )) {
		return Extend::stripslashesDeep ( $mixed );
	} else {
		return $mixed;
	}
}

function search_color($val, $k) {
	return preg_replace ( "/($k)/i", "<span class=\"findText\">\\1</span>", $val );
}

/**
 * Get either a Gravatar URL or complete image tag for a specified email address.
 *
 * @param string $email The email address
 * @param string $s Size in pixels, defaults to 80px [ 1 - 512 ]
 * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
 * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
 * @param boole $img True to return a complete IMG tag False for just the URL
 * @param array $atts Optional, additional key/value attributes to include in the IMG tag
 * @return String containing either just a URL or a complete image tag
 * @source http://gravatar.com/site/implement/images/php/
 */
function get_gravatar($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array()) {
	$url = 'http://www.gravatar.com/avatar/';
	$url .= md5 ( strtolower ( trim ( $email ) ) );
	$url .= "?s=$s&d=$d&r=$r";
	if ($img) {
		$url = '<img src="' . $url . '"';
		foreach ( $atts as $key => $val )
			$url .= ' ' . $key . '="' . $val . '"';
		$url .= ' />';
	}
	return $url;
}

/**
 * Check if search engines are blocked.
 * 
 */
function tprivacy() {
	if ('1' != C ( 'blogPublic' )) {
		return "<p><a href='" . U ( 'Admin/Options/privacy' ) . "' title='您的站点当前要求搜索引擎不索引其中内容'>当前屏蔽搜索引擎的访问</a></p>";
	} else {
		return '';
	}
}

/**
 * Display a noindex meta tag if required by the blog configuration.
 *
 * If a blog is marked as not being public then the noindex meta tag will be
 * output to tell web robots not to index the page content.
 *
 */
function noindex() {
	// If the blog is not public, tell robots to go away.
	if ('0' == C ( 'blogPublic' ))
		echo "<meta name='robots' content='noindex,nofollow' />\n";
}

/**
 * Display the robot.txt file content.
 *
 * The echo content should be with usage of the permalinks or for creating the
 * robot.txt file.
 *
 */
function do_robots() {
	header ( 'Content-Type: text/plain; charset=utf-8' );
	$output = '';
	$output .= "#\r\n# robots.txt for ThinkBLOG\r\n#\r\n\r\n";
	$public = D ( 'Options' )->getOptions ( 'blogPublic' );
	if ('0' == $public) {
		$output .= "User-agent: *\r\n";
		$output .= "Disallow: /\r\n";
	} else {
		$output .= "User-agent: *\r\n";
		$output .= "Disallow: /Apps/\r\n";
		$output .= "Disallow: /Public/\r\n";
		$output .= "Disallow: /Temp/\r\n";
		$output .= "Disallow: /ThinkPHP/\r\n";
		$output .= "Disallow: /Uploads/\r\n";
	}
	$filename = 'robots.txt';
	return file_put_contents ( $filename, $output );
}